package com.gamesa.osb.reports.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.sql.DataSource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.gamensa.osb.reports.model.OSBData;
import com.gamesa.osb.reports.dao.OSBDataDao;
import com.gamesa.osb.reports.utils.Constants;
import com.gamesa.osb.reports.utils.DataOSBMapper;

public class OSBDataDaoImpl implements OSBDataDao {

	private DataSource datasource;  
	private JdbcTemplate jdbcTemplate;
	
//	private String maxRegisters;

	private final static Logger log = LogManager.getLogger(OSBDataDaoImpl.class);
	
	public OSBDataDaoImpl(){}
	
	@Override
	public List<OSBData> getServicesData(String application, Date from, Date to) {
		
//		maxRegisters = getProperty("resource.max.services");
		
		if (from == null){
			from = new Date(0);
		}
		if (to == null){
			to = new Date();
		}
		List<OSBData> listado = null;
		try{
			listado =  jdbcTemplate
		    .query(Constants.APPLICATION_CLIENT_QUERY, 
		    		new Object[] { from, to, application, application}, 
		    		new DataOSBMapper());
 	
	    } catch(DataAccessException e){
			log.error("Error de acceso a la base de datos en getServicesData");
	    	e.printStackTrace();
	    } catch (Exception e){
			log.error("Error de en getServicesData");
	    	e.printStackTrace();
	    }
		return listado;
	}

	@Override
	public List<OSBData> getApplicationsData(String service, Date from, Date to) {

//		maxRegisters = getProperty("resource.max.applications");
		
		if (from == null){
			from = new Date(0);
		}
		if (to == null){
			to = new Date();
		}
		List<OSBData> listado = null;
		try{
			listado =  jdbcTemplate
		    .query(Constants.PROXY_SERVICE_QUERY, 
		    		new Object[] { from, to, service}, 
		    		new DataOSBMapper());

	    } catch(DataAccessException e){
			log.error("Error de acceso a la base de datos en getApplicationsData");
	    	e.printStackTrace();
	    } catch (Exception e){
			log.error("Error de en getApplicationsData");
	    	e.printStackTrace();
	    }
		return listado;
	}

//	private String getProperty(String property) {
//		try {
//		      ResourceBundle rb = ResourceBundle.getBundle("messages.properties");
//		      
//		      return rb.getString(property);
//		 
//		    } catch (MissingResourceException mre) {
//		      mre.printStackTrace();
//		    }
//		return "0";
//	}
	
	public DataSource getDatasource() {
		return datasource;
	}

	public void setDatasource(DataSource datasource) {
		this.datasource = datasource;     
		this.jdbcTemplate = new JdbcTemplate(datasource);
	}
	
}
